package dev.werillib.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.view.View
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView

/**
 * create by weril 2018/11/30
 */
class LineItemDecoration(
    context: Context,
    @ColorRes lineColor: Int,
    lineHeightPixel: Int = 1,
    isTop: Boolean = false,
    withPadding: Boolean = false,
    skipFirst: Boolean = false,
    skipLast: Boolean = false
) : RecyclerView.ItemDecoration() {
    private var paint: Paint = Paint()
    private var mDriverHeight: Int = 1
    private var isTop: Boolean = false
    private var withPadding: Boolean = false
    private var skipFirst: Boolean = false
    private var skipLast: Boolean = false

    init {
        paint.isAntiAlias = true
        paint.color = ContextCompat.getColor(context, lineColor)
        mDriverHeight = lineHeightPixel
        this.isTop = isTop
        this.withPadding = withPadding
        this.skipFirst = skipFirst
        this.skipLast = skipLast
    }

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        super.getItemOffsets(outRect, view, parent, state)
        if (isTop) {
            outRect.set(0, mDriverHeight, 0, 0)
        } else {
            outRect.set(0, 0, 0, mDriverHeight)
        }
    }

    override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        super.onDraw(c, parent, state)

        for (i in 1..parent.childCount) {
            val view: View = parent.getChildAt(i-1)
            val index = parent.getChildAdapterPosition(view)
            if (skipFirst) {
                if (index == 0) continue
            }

            if (skipLast) {
                if (index == parent.childCount - 1) continue
            }

            var left = 0f
            if (withPadding) {
                left = view.paddingLeft.toFloat()
            }
            var right: Float = view.measuredWidth.toFloat()
            if (withPadding) {
                right = (view.measuredWidth - view.paddingRight).toFloat()
            }

            var top: Float
            var bottom: Float

            if (isTop) {
                top = (view.top - mDriverHeight).toFloat()
                bottom = (view.top).toFloat()
            } else {
                top = view.bottom.toFloat()
                bottom = (view.bottom + mDriverHeight).toFloat()
            }
            c.drawRect(left, top, right, bottom, paint)
        }
    }
}

